package mz.co.research.util.importer;

import java.io.InputStream;

import mz.co.framework.error.SystemException;
import mz.co.research.util.parser.metadata.MetaAnswer;
import mz.co.research.util.parser.metadata.MetaAnswerDomain;
import mz.co.research.util.parser.metadata.MetaAnswerDomainItem;
import mz.co.research.util.parser.metadata.MetaForm;
import mz.co.research.util.parser.metadata.MetaQuestion;
import mz.co.research.util.parser.metadata.MetaResearch;

import com.thoughtworks.xstream.XStream;

public class ResearchParser {

	private static final XStream xstream = new XStream();

	private ResearchParser() {
	}

	static {

		xstream.alias("research", MetaResearch.class);
		xstream.alias("form", MetaForm.class);
		xstream.alias("question", MetaQuestion.class);
		xstream.alias("answer", MetaAnswer.class);
		xstream.alias("answerDomain", MetaAnswerDomain.class);
		xstream.alias("answerDomainItem", MetaAnswerDomainItem.class);

		xstream.addImplicitCollection(MetaResearch.class, "forms");
		xstream.addImplicitCollection(MetaForm.class, "questions");
		xstream.addImplicitCollection(MetaAnswerDomain.class,
				"answerDomainItems");

		xstream.useAttributeFor(MetaResearch.class, "code");
		xstream.useAttributeFor(MetaResearch.class, "description");

		xstream.useAttributeFor(MetaForm.class, "code");
		xstream.useAttributeFor(MetaForm.class, "description");

		xstream.useAttributeFor(MetaQuestion.class, "description");
		xstream.useAttributeFor(MetaQuestion.class, "answerType");

		xstream.useAttributeFor(MetaAnswer.class, "fetch");

		xstream.useAttributeFor(MetaAnswerDomain.class, "code");
		xstream.useAttributeFor(MetaAnswerDomain.class, "description");

		xstream.useAttributeFor(MetaAnswerDomainItem.class, "code");
		xstream.useAttributeFor(MetaAnswerDomainItem.class, "description");
	}

	public static MetaResearch parse(InputStream descriptor)
			throws SystemException {

		return (MetaResearch) xstream.fromXML(descriptor);

	}

	public static String unparse(MetaResearch metaResearch)
			throws SystemException {

		return xstream.toXML(metaResearch);

	}
}
